<template>
  <PageLayout full>
    <template #header>
      <HeaderLayout show-back :header-style="headerStyle">
        <view>{{ $t('UseGuide.Navigate.Title') }}</view>
      </HeaderLayout>
    </template>
    <view class="use-guide-container">
      <view class="appliance-info bg disflay-between com-padd" :class="{ 'empty-info': isEmpty }">
        <view class="appliance-name">{{ options.type }}</view>
        <view class="appliance-vib">{{ options.vib }}</view>
      </view>
      <!-- 顶部视频 -->
      <view class="new-guide-video bg com-padd" v-if="topVideoData && topVideoData?.hasVideo === '1'">
        <view class="new-guide-box">
          <view class="top-title-box disflay-between">
            <view class="new-guide-title opcityNine">{{ topVideoData.title }}</view>
            <view class="look-over" v-if="!isShowHeaderVedio" @click="showHeaderVedio">
              <text class="opcitySix">{{ $t('UseGuide.TopGuide.Check.Text') }}</text>
              <image class="arrow-right" :src="'/static/ic_right_arrow.png'"></image>
            </view>
          </view>
          <view class="top-des disflay-between" v-if="isShowHeaderVedio">
            <view class="new-guide-des">{{ $t('UseGuide.TopGuide.Des.Text') }}</view>
            <view class="new-guide-close" @click="showHeaderVedio">{{ $t('UseGuide.TopGuide.Button') }}</view>
          </view>
          <view class="top-video" v-if="isShowHeaderVedio">
            <TrackButton
              track-id="play_guide_video"
              :track-data="trackData"
              :type="TrackType.ApplianceDetail"
              :button-id="'Appliance.Setting.UserGuide.PlayVideo'"
            >
              <video
                class="video-box"
                id="myVideo"
                :src="topVideoData.url"
                @error="videoErrorCallback"
                show-center-play-btn="true"
                show-play-btn="true"
                controls
                @play="videoTrack"
                @click="videoTrack"
              ></video>
            </TrackButton>
          </view>
        </view>
      </view>
      <!-- 使用指南 -->
      <view class="use-guide-box bg padd-left" v-if="useGuideList.length > 0 || pairingGuidePdf">
        <view class="title-box disflay-between">
          <view class="new-guide-title">{{ $t('UseGuide.UseGuide.Lable') }}</view>
        </view>
        <!-- pdf -->
        <view v-if="pairingGuidePdf" class="guide-box" @click="openPdf(installationUseGrid[0])">
          <alt-picture class="guide-img" :src="'/pages/my/static/ic_pdf.jpg'" />
          <view class="guide-cont">
            <view class="cont-title">说明书</view>
          </view>
        </view>
        <!-- list -->
        <view v-if="useGuideList.length > 0" class="guide-view" v-for="(item, index) in useGuideList" :key="index">
          <view
            class="guide-box"
            v-if="index < (isShowUseGuideMore ? useGuideList.length : 2)"
            @click="jumpLookVideo(item, 3, '使用指南')"
          >
            <alt-picture class="guide-img" :src="item.image" />
            <view class="guide-cont">
              <view class="cont-title">{{ item.title }}</view>
              <view class="cont-look">
                <image class="look-img" src="/static/ic_look.png"></image>
                <view class="look-number">{{ lookNumber(item.lookCount) }}{{ $t('UseGuide.ReopleRead.Text') }}</view>
              </view>
            </view>
          </view>
        </view>
        <view class="more-box" v-if="useGuideList.length > 2 && !isShowUseGuideMore" @click="showMoreUseGuide">
          <image class="more-img" :src="'/pages/my/static/ic_more_bottom.png'"></image>
          <view class="more-text">{{ $t('UseGuide.MoreOver.Button') }}</view>
        </view>
      </view>
      <!-- 清洁保养 -->
      <view class="use-guide-box bg padd-left" v-if="cleaningMaintenanceList.length > 0">
        <view class="title-box disflay-between">
          <view class="new-guide-title">{{ $t('UseGuide.CleaningMaintenance.Lable') }}</view>
        </view>
        <view
          class="guide-view"
          v-for="(item, index) in cleaningMaintenanceList"
          :key="index"
          @click="jumpLookVideo(item, 4, '清洁保养')"
        >
          <view class="guide-box" v-if="index < (isShowcleaningMaintenanceMore ? cleaningMaintenanceList.length : 2)">
            <alt-picture class="guide-img" :src="item.image" />
            <view class="guide-cont">
              <view class="cont-title">{{ item.title }}</view>
              <view class="cont-look">
                <image class="look-img" src="/static/ic_look.png"></image>
                <view class="look-number">{{ lookNumber(item.lookCount) }}{{ $t('UseGuide.ReopleRead.Text') }}</view>
              </view>
            </view>
          </view>
        </view>
        <view
          class="more-box"
          v-if="cleaningMaintenanceList.length > 2 && !isShowcleaningMaintenanceMore"
          @click="showMoreCleaningMaintenance"
        >
          <image class="more-img" :src="'/pages/my/static/ic_more_bottom.png'"></image>
          <view class="more-text">{{ $t('UseGuide.MoreOver.Button') }}</view>
        </view>
      </view>
      <!-- 常见问题 -->
      <view class="use-guide-box bg padd-left" v-if="commonProblemList.length > 0">
        <view class="title-box disflay-between">
          <view class="new-guide-title">{{ $t('UseGuide.CommonProblem.Lable') }}</view>
        </view>
        <view
          class="guide-view"
          v-for="(item, index) in commonProblemList"
          :key="index"
          @click="jumpLookVideo(item, 5, '常见问题')"
        >
          <view class="guide-box" v-if="index < (isShowCommonProblemMore ? commonProblemList.length : 2)">
            <alt-picture class="guide-img" :src="item.image" />
            <view class="guide-cont">
              <view class="cont-title">{{ item.title }}</view>
              <view class="cont-look">
                <image class="look-img" src="/static/ic_look.png"></image>
                <view class="look-number">{{ lookNumber(item.lookCount) }}{{ $t('UseGuide.ReopleRead.Text') }}</view>
              </view>
            </view>
          </view>
        </view>
        <view
          class="more-box"
          v-if="commonProblemList.length > 2 && !isShowCommonProblemMore"
          @click="showMoreCommonProblem"
        >
          <image class="more-img" :src="'/pages/my/static/ic_more_bottom.png'"></image>
          <view class="more-text">{{ $t('UseGuide.MoreOver.Button') }}</view>
        </view>
      </view>
      <!-- 安装贴士 -->
      <view class="use-guide-box bg padd-left" v-if="installationTipsList.length > 0 || installationTipsPDF.length > 0">
        <view class="title-box disflay-between">
          <view class="new-guide-title">{{ $t('UseGuide.InstallationTips.Lable') }}</view>
        </view>
        <!-- pdf -->
        <view
          class="guide-box"
          v-if="installationTipsPDF.length > 0"
          v-for="(item, index) in installationTipsPDF"
          :key="index"
          @click="openPdf(item)"
        >
          <alt-picture class="guide-img" :src="'/pages/my/static/ic_pdf.jpg'" />
          <view class="guide-cont">
            <view class="cont-title">{{ item.title }}</view>
          </view>
        </view>
        <!-- list -->
        <view
          v-if="installationTipsList.length > 0"
          class="guide-view"
          v-for="(item, index) in installationTipsList"
          :key="index"
          @click="jumpLookVideo(item, 2, '安装贴士')"
        >
          <view class="guide-box" v-if="index < (isShowInstallationTipsMore ? installationTipsList.length : 2)">
            <alt-picture class="guide-img" :src="item.image" />
            <view class="guide-cont">
              <view class="cont-title">{{ item.title }}</view>
              <view class="cont-look">
                <image class="look-img" src="/static/ic_look.png"></image>
                <view class="look-number">{{ lookNumber(item.lookCount) }}{{ $t('UseGuide.ReopleRead.Text') }}</view>
              </view>
            </view>
          </view>
        </view>
        <view
          class="more-box"
          v-if="installationTipsList.length > 2 && isShowInstallationTipsMore"
          @click="showMoreInstallationTips"
        >
          <image class="more-img" :src="'/pages/my/static/ic_more_bottom.png'"></image>
          <view class="more-text">{{ $t('UseGuide.MoreOver.Button') }}</view>
        </view>
      </view>
    </view>
    <view class="empty-box" v-if="isEmpty">
      <AltPicture class="empty-icon-useGuide"></AltPicture>
    </view>
  </PageLayout>
</template>
<script lang="ts">
export type UseGuidePDFType = {}
</script>
<script setup lang="ts">
import PageLayout from '@/layout/page/page.vue'
import HeaderLayout from '@/layout/page/header.vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { trackEvent, TrackType } from '@/dataReport/tracks'
import {
  getTopVideoListByVib,
  type TopVideoListByVibType,
  type InformationType,
  type DocumentsType,
  getInformationVideoListByVib,
} from '@/api/content'
import { useI18n } from 'vue-i18n'
import { safeTrack } from '@/dataReport/dataReportUtil'
import netconfig from '@/config/netconfig'
import AltPicture from '@/common/altPicture.vue'
const i18n = useI18n()

const headerStyle = {
  backgroundColor: '#fff',
}
const defaultVib = 'CSG7564B1W'

const options = reactive({
  vib: '',
  name: '',
  type: '',
})

const vib = ref('')
const interfaceNum = ref([0, 0, 0, 0])
const isShowHeaderVedio = ref(true)
const isShowUseGuideMore = ref(false)
const isShowcleaningMaintenanceMore = ref(false)
const isShowCommonProblemMore = ref(false)
const isShowInstallationTipsMore = ref(false)
const trackData = ref({})
const topVideoData = ref<TopVideoListByVibType | null>(null)
const useGuideList = ref<InformationType[]>([])
const cleaningMaintenanceList = ref<InformationType[]>([])
const commonProblemList = ref<InformationType[]>([])
const installationTipsList = ref<InformationType[]>([])
const installationTipsPDF = ref<DocumentsType[]>([])
const installationUseGrid = ref<DocumentsType[]>([])
onLoad((query) => {
  options.type = decodeURIComponent(query?.type)
  options.vib = query?.vib
  options.name = decodeURIComponent(query?.name)
  vib.value = query?.vib != '' ? query?.vib : defaultVib
  getTopVideoList(vib.value)
})
onShow(() => {
  getGuideInformationList(vib.value)
})
function videoTrack() {
  trackData.value = {
    video_name: topVideoData.value?.title,
    video_id: topVideoData.value?.id,
  }
}
const isEmpty = computed(() => {
  return (
    !topVideoData.value &&
    !pairingGuidePdf.value &&
    useGuideList.value.length <= 0 &&
    cleaningMaintenanceList.value.length <= 0 &&
    commonProblemList.value.length <= 0 &&
    installationTipsList.value.length <= 0 &&
    installationTipsPDF.value.length <= 0
  )
})

function lookNumber(lookCount: string) {
  lookCount = lookCount.length < 4 ? '0.1万' : (Number(lookCount) / 10000).toFixed(1) + '万'
  return lookCount
}

function showHeaderVedio() {
  isShowHeaderVedio.value = !isShowHeaderVedio.value
}
function showMoreUseGuide() {
  isShowUseGuideMore.value = !isShowUseGuideMore.value
}
function showMoreCleaningMaintenance() {
  isShowcleaningMaintenanceMore.value = !isShowcleaningMaintenanceMore.value
}
function showMoreCommonProblem() {
  isShowCommonProblemMore.value = !isShowCommonProblemMore.value
}
function showMoreInstallationTips() {
  isShowInstallationTipsMore.value = !isShowInstallationTipsMore.value
}
/**
 *  获取头部视频接口
 * @param vib
 */
async function getTopVideoList(vib: string) {
  const res = await getTopVideoListByVib(vib)
  if (res.data.length > 0) {
    topVideoData.value = res.data[0]
    trackData.value = {
      video_name: topVideoData.value?.title,
      video_id: topVideoData.value?.url,
    }
  }
}
/**
 * 获取底部咨询数据
 * @param type
 * @param vib
 */
const pairingGuidePdf = ref('')
async function getGuideInformationList(vib: string) {
  let data = {
    vib,
  }
  const res = await getInformationVideoListByVib(data)
  let { information, documents } = res.data[0]
  if (information && information.length !== 0) {
    useGuideList.value = information.filter((item) => item.type === '3') //使用指南
    cleaningMaintenanceList.value = information.filter((item) => item.type === '4') //清洁保养
    commonProblemList.value = information.filter((item) => item.type === '5') //常见问题
    installationTipsList.value = information.filter((item) => item.type === '2') //安装贴士
  }
  if (documents && documents.length !== 0) {
    // 接口返回多个IU(安装贴士)、II（使用指南）仅显示第一个
    documents.forEach((item) => {
      let IUFlag = item.docTypes.some((item) => item === 'IU')
      let IIFlag = item.docTypes.some((item) => item === 'II')
      if (IIFlag && installationUseGrid.value.length === 0) {
        installationUseGrid.value.push(item)
      }
      if (IUFlag && installationTipsPDF.value.length === 0) {
        installationTipsPDF.value.push(item)
      }
    })
  }
  if (res.data && res.data[0].pairingGuidePdf) {
    pairingGuidePdf.value = installationUseGrid.value[0].downloadUrl
  }
}

function videoErrorCallback() {
  uni.showToast({
    title: i18n.t('UseGuide.Video.Error.Title'),
    duration: 2000,
  })
}
function jumpLookVideo(item: InformationType, index: number, navigateTitle: string) {
  let { url, id, hasVideo, title } = item
  safeTrack(() => {
    trackEvent(
      'check_article_actionhandler',
      { article_id: item.id, article_name: item.title, label_name: item.type },
      TrackType.ApplianceDetail,
      'Appliance.UserRepotr.Artile.Select'
    )
  })
  uni.navigateTo({
    url: `/pages/my/guideVideo/guideVideo?hasVideo=${hasVideo}&guideVideoUrl=${url}&id=${id}&type=${index}&title=${title}&navigateTitle=${navigateTitle}`,
  })
}
/**
 * 打开pdf
 */
function openPdf(item: DocumentsType) {
  safeTrack(() => {
    trackEvent(
      'before_check_article_actionhandler',
      { article_id: item.code, article_name: item.title, label_name: '2' },
      TrackType.ApplianceDetail,
      'Appliance.UserRepotr.Artile.Select'
    )
  })
  uni.showLoading({
    title: i18n.t('APP.Common.Loading.Text'),
    mask: true,
  })
  uni.downloadFile({
    url: item.downloadUrl,
    success: function (res) {
      wx.hideLoading()
      const filePath = res.tempFilePath
      uni.openDocument({
        filePath,
      })
      safeTrack(() => {
        trackEvent(
          'check_article_actionhandler',
          { article_id: item.code, article_name: item.title, successOrNot: true, label_name: '2' },
          TrackType.ApplianceDetail,
          'Appliance.UserRepotr.Artile.Select'
        )
      })
    },
    fail: function (error) {
      uni.hideLoading()
      uni.showToast({
        title: i18n.t('APP.Common.OpenFail.Text'),
        icon: 'error',
      })
      safeTrack(() => {
        trackEvent(
          'check_article_actionhandler',
          {
            article_id: item.code,
            article_name: item.title,
            successOrNot: true,
            error_code: error.code,
            response_msg: error.msg,
            label_name: '2',
          },
          TrackType.ApplianceDetail,
          'Appliance.UserRepotr.Artile.Select'
        )
      })
    },
  })
}
/**
 * 打开使用指南pdf
 */
function openUseGuidePdf() {
  uni.showLoading({
    title: i18n.t('APP.Common.Loading.Text'),
    mask: true,
  })
  uni.downloadFile({
    url: netconfig.ASSETSPRE + pairingGuidePdf.value,
    success: function (res) {
      wx.hideLoading()
      const filePath = res.tempFilePath
      uni.openDocument({
        filePath,
      })
      safeTrack(() => {
        trackEvent(
          'check_article_actionhandler',
          {
            article_id: '001',
            article_name: pairingGuidePdf.value,
            successOrNot: true,
            label_name: '3',
          },
          TrackType.ApplianceDetail
        )
      })
    },
    fail: function (error) {
      safeTrack(() => {
        trackEvent(
          'check_article_actionhandler',
          {
            article_id: '001',
            article_name: pairingGuidePdf.value,
            successOrNot: false,
            label_name: '3',
          },
          TrackType.ApplianceDetail
        )
      })
      uni.hideLoading()
      uni.showToast({
        title: i18n.t('APP.Common.OpenFail.Text'),
        icon: 'error',
      })
    },
  })
}
</script>
<style scoped lang="less">
.empty-box {
  width: 100%;
  height: calc(100vh - 258rpx);
  background: #f4f4f6;
  .empty-icon-useGuide {
    width: 342px;
    height: 342px;
    margin: auto;
    display: block;
  }
}
.use-guide-container {
  width: 100%;
  background-color: #f4f4f4;
  font-family: 'PingFang SC';
  font-style: normal;

  .bg {
    background-color: #fff;
  }
  .disflay-between {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .com-padd {
    padding: 0 32rpx;
  }
  .padd-left {
    padding-left: 32rpx;
  }
  .top-title-box {
    line-height: 44rpx;
  }
  .opcityNine {
    opacity: 0.9;
  }
  .opcitySix {
    opacity: 0.6;
  }
  .arrow-right {
    width: 16rpx;
    height: 28rpx;
    margin-left: 24rpx;
  }
  .look-over {
    display: flex;
    align-items: center;
    text {
      font-weight: 400;
      font-size: 32rpx;
      color: var(--dark-color);
    }
  }
  .title-box {
    height: 88rpx;
    line-height: 88rpx;
    .new-guide-title {
      font-weight: 500;
      font-size: 32rpx;
      color: var(--dark-color);
    }
  }
  .guide-box {
    display: flex;
    height: 132rpx;
    padding: 20rpx 0 20rpx;
    border-top: 2rpx solid rgba(233, 233, 237, 1);
    .guide-img {
      width: 132rpx;
      height: 132rpx;
      background: #f4f4f4;
      margin-right: 24rpx;
    }
    .guide-cont {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      width: calc(100% - 156rpx);
      .cont-title {
        font-weight: 500;
        font-size: 32rpx;
        line-height: 44rpx;
        color: var(--dark-color);
      }
      .cont-look {
        display: flex;
        align-items: center;
        .look-img {
          width: 36rpx;
          height: 20rpx;
          margin-right: 16rpx;
        }
        .look-number {
          font-weight: 500;
          font-size: 24rpx;
          color: var(--dark-color);
          opacity: 0.4;
        }
      }
    }
  }
  .more-box {
    height: 70rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    .more-img {
      width: 30rpx;
      height: 30rpx;
      margin-right: 10rpx;
    }
    .more-text {
      font-weight: 500;
      font-size: 28rpx;
      line-height: 40rpx;
      color: var(--dark-color);
      opacity: 0.4;
    }
  }
  .appliance-info {
    height: 90rpx;
    margin-bottom: 26rpx;
    border-top: 1rpx solid rgba(233, 233, 237, 1);
    position: relative;
    &::after {
      display: block;
      content: '';
      position: absolute;
      width: calc(100% - 32rpx);
      left: 32rpx;
      height: 1rpx;
      bottom: 0;
      background-color: rgba(233, 233, 237, 1);
    }
    .appliance-name {
      font-weight: 500;
      opacity: 0.9;
      color: #2d3746;
      font-size: 32rpx;
    }
    .appliance-vib {
      color: #2d3746;
      font-size: 32rpx;
      font-weight: 400;
      opacity: 0.6;
    }
  }
  .empty-info {
    margin-bottom: 0;
  }
  .new-guide-box {
    padding: 24rpx 0;
    margin-bottom: 24rpx;
    .top-des {
      padding-bottom: 30rpx;
      .new-guide-des {
        font-weight: 400;
        font-size: 24rpx;
        line-height: 34rpx;
        color: var(--dark-color);
        opacity: 0.6;
      }
      .new-guide-close {
        font-weight: 500;
        font-size: 24rpx;
        line-height: 34rpx;
        color: var(--primary-color);
      }
    }
    .top-video {
      width: 100%;
      height: 404rpx;
      background-color: #f4f4f4;
      .video-box {
        width: 100%;
        height: 100%;
      }
    }
  }
  .use-guide-box {
    border-top: 1rpx solid rgba(233, 233, 237, 1);
    border-bottom: 1rpx solid rgba(233, 233, 237, 1);
    margin-bottom: 24rpx;
  }
}
</style>
